<template>
  <q-dialog class="my-dialog-form" v-model="isFlagShow">
    <q-card class="my-card">
      <q-toolbar class="row items-center my-form-header">
        <div>
          {{dlgTitle}}
        </div>
        <q-space />
        <q-btn flat round dense icon="mdi-close" @click="close"/>
      </q-toolbar>
      <q-separator />
      <q-card-setion class="q-mx-sm">
        <q-scroll-area class="my-form-container">
          <table class="my-form-table">
            <tr class="my-row-height">
              <td class="my-label"><span style="color: red">**</span>账号：</td>
              <td class="my-value">
                <q-input
                  outlined
                  dense
                  v-model="param.nick"
                  @blur="v$.nick.$touch()"
                  :error="v$.nick.$error"
                  error-message="请输入不少于2个字符！"
                />
              </td>
              <td class="my-label"><span style="color: red">**</span>密码：</td>
              <td class="my-value">
                <q-input
                  outlined
                  dense
                  v-model="param.password"
                  @blur="v$.password.$touch()"
                  :error="v$.password.$error"
                  error-message="请输入不少于6个字符的密码！"
                />
              </td>
            </tr>
            <tr class="my-row-height">
              <td class="my-label"><span style="color: red">**</span>公司：</td>
              <td class="my-value">
                <q-select
                  class="my-select-box"
                  dense
                  outlined
                  options-dense
                  clearable
                  :options="companyArr"
                  option-value="label"
                  emit-value
                  options-selected-class="teal"
                  v-model="param.company"
                  @update:model-value="companyItemSelected"
                  @blur="v$.company.$touch()"
                  :error="v$.company.$error"
                  error-message="请选择所属公司！"
                />
              </td>
              <td class="my-label"><span style="color: red">**</span>部门：</td>
              <td class="my-value">
                <q-select
                  class="my-select-box"
                  dense
                  outlined
                  options-dense
                  clearable
                  :options="departmentList"
                  option-value="label"
                  emit-value
                  options-selected-class="teal"
                  v-model="param.department"
                  @blur="v$.department.$touch()"
                  :error="v$.department.$error"
                  error-message="请选择所在部门！"
                />
              </td>
            </tr>
            <tr class="my-row-height">
              <td class="my-label">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;姓名：</td>
              <td class="my-value">
                <q-input
                  outlined
                  dense
                  v-model="param.cname"
                />
              </td>
              <td class="my-label">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;性别：</td>
              <td class="my-value">
                <q-radio v-model="param.sex" val="男" label="男" color="teal" />
                <q-radio v-model="param.sex" val="女" label="女" color="orange" />
              </td>
            </tr>
            <tr class="my-row-height">
              <td class="my-label">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;电话：</td>
              <td class="my-value">
                <q-input
                  dense
                  outlined
                  v-model="param.telephone"
                  @blur="v$.telephone.$touch()"
                  :error="v$.telephone.$error"
                  error-message="电话号码只能为数字！"
                />
              </td>
              <td class="my-label">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;邮箱：</td>
              <td class="my-value">
                <q-input
                  dense
                  outlined
                  v-model="param.email"
                  @blur="v$.email.$touch()"
                  :error="v$.email.$error"
                  error-message="请检查邮箱格式是否有效！"
                />
              </td>
            </tr>
            <tr class="my-row-height">
              <td class="my-label">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;微信：</td>
              <td class="my-value">
                <q-input
                  dense
                  outlined
                  v-model="param.messenger"
                  @blur="v$.messenger.$touch()"
                  :error="v$.messenger.$error"
                  error-message="请检查微信格式是否有效！"
                />
              </td>
              <td class="my-label">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;工号：</td>
              <td class="my-value">
                <q-input
                  outlined
                  dense
                  v-model="param.employeeCode"
                />
              </td>
            </tr>
            <tr class="my-row-height">
              <td class="my-label">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;职位：</td>
              <td class="my-value">
                <q-select
                  dense
                  outlined
                  options-dense
                  :options="positionTypeArr"
                  option-value="label"
                  emit-value
                  options-selected-class="teal"
                  v-model="param.position"
                />
              </td>
              <td class="my-label">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;角色：</td>
              <td class="my-value">
                <q-select
                  class="my-select-box"
                  dense
                  outlined
                  clearable
                  options-dense
                  :options="roleArr"
                  option-value="label"
                  emit-value
                  options-selected-class="teal"
                  v-model="param.role"
                />
              </td>
            </tr>
            <tr class="my-row-height">
              <td class="my-label">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;范围：</td>
              <td class="my-value">
                <q-input
                  outlined
                  dense
                  v-model="param.privilege"
                />
              </td>
              <td class="my-label">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;状态：</td>
              <td class="my-value">
                <q-select
                  dense
                  outlined
                  options-dense
                  :options="statusTypeArr"
                  option-value="label"
                  emit-value
                  options-selected-class="teal"
                  v-model="param.userStatus"
                />
              </td>
            </tr>
          </table>
        </q-scroll-area>
      </q-card-setion>
      <q-separator />
      <div class="q-gutter-sm my-form-footer">
        <q-btn
          unelevated
          dense
          label="提交"
          type="submit"
          color="teal-3"
          @click="onSubmit"
          style="width: 80px"
        />
        <q-btn
          unelevated
          dense
          label="重置"
          type="reset"
          color="orange-3"
          @click="onReset"
          style="width: 80px"
        />
      </div>
    </q-card>
  </q-dialog>
</template>

<script lang="ts">
import { defineAsyncComponent, defineComponent, onMounted, ref, toRef, toRefs, PropType, watch } from 'vue';
import { isObjectEmpty } from '../../../util/utils';
import api from 'axios'
import { required, numeric, email, minLength } from '@vuelidate/validators'
import { useVuelidate } from '@vuelidate/core';
import { sysBaseVOAPI } from '../../../util/SysBaseConst';
import { cataItem } from '../../../hook/common/useCatalogType';
import { useCatalogTool } from 'src/hook/common/useCatalogTool';

const AmyIconSelect = defineAsyncComponent(() => import('components/basic/AmyIconSelect.vue'));
import { UserItem, UserItemVO } from './UserModel';


export default defineComponent({
  cname: 'UserDlg',
  components: {
    AmyIconSelect
  },
  props: {
    itemData: {
      type: Object as PropType<UserItem>,
      required: true
    },

    statusTypeArr: {
      type: Array as PropType<cataItem[]>,
      required: true
    },

    sexTypeArr: {
      type: Array as PropType<cataItem[]>,
      required: true
    },
    positionTypeArr: {
      type: Array as PropType<cataItem[]>,
      required: true
    },
    departmentTypeArr: {
      type: Array as PropType<cataItem[]>,
      required: true
    },
    roleArr: {
      type: Array as PropType<cataItem[]>,
      required: true
    },
    companyArr: {
      type: Array as PropType<cataItem[]>,
      required: true
    }
  },
  emits: ['submit-user-item', 'cancel-user-item'],
  setup (props, context) {
    //数据解构
    const {
      itemData,
      sexTypeArr,
      statusTypeArr,
      positionTypeArr,
      roleArr,
      companyArr,
      departmentTypeArr
    } = toRefs(props);

    //*******************************
    //      目录操作
    //*******************************
    const {
      findCatalogLabel,
      findCatalogId
    } = useCatalogTool();

    //*******************************
    //      表单项
    //*******************************
    //窗口显示
    let isFlagShow = ref(false);

    //窗口标题
    let dlgTitle = ref('');

    //界面数据
    let param = ref<UserItemVO>({
      id: 0,
      nick: '',
      password: '',
      cname: '',
      icon: '', //icon
      sex: '',
      email: '',
      telephone: '',
      messenger: '',
      position: '',
      department: '',
      company: '',
      employeeCode: '',
      userStatus: '',
      role: '',
      privilege: 0,
      sortCode: ''
    });

    //部门列表
    let departmentList = ref<cataItem[]>([]);

    //关闭窗口
    const close = () => {
      isFlagShow.value = false;
      context.emit('cancel-user-item');
    }

    //显示窗口
    const show = (text: string) => {
      isFlagShow.value = true;
      dlgTitle.value = text;
    }

    //提交窗口
    const onSubmit = () => {
      v$.value.$validate();
      if (v$.value.$error) {
        alert('输入参数校验错误!');
      } else {
        isFlagShow.value = false;
        let item: UserItem = {
          id: param.value.id,
          nick: param.value.nick,
          password: param.value.password,
          cname: param.value.cname,
          icon: param.value.icon,
          sex: findCatalogId(sexTypeArr.value, param.value.sex),
          email: param.value.email,
          telephone: param.value.telephone,
          messenger: param.value.messenger,
          positionId: findCatalogId(positionTypeArr.value, param.value.position),
          departmentId: findCatalogId(departmentTypeArr.value, param.value.department),
          companyId: findCatalogId(companyArr.value, param.value.company),
          employeeCode: param.value.employeeCode,
          userStatusId: findCatalogId(statusTypeArr.value, param.value.userStatus),
          roleId: findCatalogId(roleArr.value, param.value.role),
          privilege: param.value.privilege,
          sortCode: param.value.sortCode,
          createTime: '',
          createUserId: 0,
          updateTime: '',
          updateUserId: 0
        };

        //发送数据
        context.emit('submit-user-item', item);
      }
    }

    //重置
    const onReset = () => {
      if (param.value) {
        param.value.nick = '';
        param.value.password = '';
        param.value.cname = '';
        param.value.icon = '';
        param.value.sex = '';
        param.value.email = '';
        param.value.telephone = '';
        param.value.messenger = '';
        param.value.position = '';
        param.value.company = '';
        param.value.employeeCode = '';
        param.value.userStatus = '';
        param.value.role = '';
        param.value.privilege = 0;
        param.value.sortCode = '';
      }

      //表单验证初始化
      v$.value.$reset();
    }

    //更新图标
    const refreshIcon = (icon: string) => {
      param.value.icon = icon;
    }

    //公司发生变化
    const companyItemSelected = () => {
      api.post(sysBaseVOAPI.DEPARTMENT_VO_MAP, {
        cname: param.value.company
      }).then((res) => {
        departmentList.value = res.data.data;
        param.value.department = '';
      })
    }

    //*******************************
    //      表单校验
    //*******************************
    //配置校验规则
    const rules = {
      id: {},
      nick: { required, minLength: minLength(2) },
      password: { required, minLength: minLength(6) },
      cname: {},
      icon: { },
      sex: {},
      email: { required, email },
      telephone: { numeric },
      messenger: {},
      position: {},
      department: { required },
      company: { required },
      employeeCode: {},
      userStatus: {},
      role: {},
      privilege: {},
      sortCode: {}
    }

    //使用vuelidate，建立变量对应的校验规则
    const v$ = useVuelidate(rules, {
      id: toRef(param.value, 'id'),
      nick: toRef(param.value, 'nick'),
      password: toRef(param.value, 'password'),
      cname: toRef(param.value, 'cname'),
      icon: toRef(param.value, 'icon'),
      sex: toRef(param.value, 'sex'),
      email: toRef(param.value, 'email'),
      telephone: toRef(param.value, 'telephone'),
      messenger: toRef(param.value, 'messenger'),
      position: toRef(param.value, 'position'),
      department: toRef(param.value, 'department'),
      company: toRef(param.value, 'company'),
      employeeCode: toRef(param.value, 'employeeCode'),
      userStatus: toRef(param.value, 'userStatus'),
      role: toRef(param.value, 'role'),
      privilege: toRef(param.value, 'privilege'),
      sortCode: toRef(param.value, 'sortCode')
    });


    //*******************************
    //      启动模块
    //*******************************
    //初始化
    const init = () => {
      if (!isObjectEmpty(itemData.value)) {
        param.value.id = itemData.value.id;
        param.value.nick = itemData.value.nick;
        param.value.password = itemData.value.password;
        param.value.cname = itemData.value.cname;
        param.value.icon = itemData.value.icon;
        param.value.sex = findCatalogLabel(sexTypeArr.value, itemData.value.sex);
        param.value.email = itemData.value.email;
        param.value.telephone = itemData.value.telephone;
        param.value.messenger = itemData.value.messenger;
        param.value.position = findCatalogLabel(positionTypeArr.value, itemData.value.positionId);
        param.value.department = findCatalogLabel(departmentTypeArr.value, itemData.value.departmentId);
        param.value.company = findCatalogLabel(companyArr.value, itemData.value.companyId);
        param.value.employeeCode = itemData.value.employeeCode;
        param.value.userStatus = findCatalogLabel(statusTypeArr.value, itemData.value.userStatusId);
        param.value.role = findCatalogLabel(roleArr.value, itemData.value.roleId);
        param.value.privilege = itemData.value.privilege;

        //更新部门列表
        companyItemSelected();
        if (departmentTypeArr.value) {
          departmentList.value.length = 0;
          departmentTypeArr.value.forEach((item: cataItem) => {
            departmentList.value.push(item);
          });
        }
      }

      //表单验证初始化
      v$.value.$reset();
    }

    //监听对象的所有属性
    watch(() => props.itemData, () => {
      init();
    }, { deep: true });

    //启动挂载组件
    onMounted(() => {
      init();
    })

    return {
      sexTypeArr,
      statusTypeArr,
      positionTypeArr,
      departmentTypeArr,
      roleArr,
      companyArr,

      isFlagShow,
      dlgTitle,
      departmentList,
      param,
      init,
      close,
      show,
      onSubmit,
      onReset,
      refreshIcon,
      companyItemSelected,
      v$
    }
  }
})
</script>

<style lang="scss" scoped>
.my-card {
  alignment: center;
  width: 700px;
  max-width: 800px;

  .my-form-container {
    text-align: center;
    padding: 5px 50px 5px 20px;
    height: 420px;

    .my-select-box {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }


}

</style>
